package com.nbsaas.lbs.baidu.geo;

import java.io.IOException;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nbsaas.http.Connection;
import com.nbsaas.http.HttpConnection;
import com.nbsaas.http.Connection.Method;

public class BaiduGeoUtils {

	private static String nearbyurl = "http://api.map.baidu.com/geocoder/v2/";
	private static String ak = "19fe04c380d6f64884191e21fdca9043";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//34.2395504,108.9011901 34.2395196,108.9011494 34.2395246,108.9011531
		String value = "34.27779990,108.95309828";
		LbsAddress lbs = get(value);
		System.out.println(lbs);
		System.out.println(lbs.getFormatted_address());

	}

	static LbsAddress get(String value) {
		LbsAddress lbs = new LbsAddress();
		Connection connection = HttpConnection.connect(nearbyurl);
		connection.data("ak", ak);
		connection.data("location", value);
		connection.data("pois", "0");
		/**
		 * bd09ll（百度经纬度坐标）、gcj02ll（国测局经纬度坐标）、wgs84ll（ GPS经纬度）
		 */
		connection.data("coordtype", "bd09ll");

		connection.data("output", "json");
		connection.method(Method.GET);
		String msg = null;
		try {
			msg = connection.execute().body();
			JsonParser jsonParser = new JsonParser();
			JsonObject resp = jsonParser.parse(msg).getAsJsonObject();
			JsonElement result = resp.get("result");
			if (result != null && result.isJsonObject()) {
				JsonObject r = result.getAsJsonObject();
				lbs.setFormatted_address(getkey(r, "formatted_address"));

				JsonObject address_component = r.get("addressComponent")
						.getAsJsonObject();
				lbs.setNation(getkey(address_component, "nation"));
				lbs.setProvince(getkey(address_component, "province"));
				lbs.setCity(getkey(address_component, "city"));
				lbs.setDistrict(getkey(address_component, "district"));
				lbs.setStreet(getkey(address_component, "street"));
				lbs.setStreet_number(getkey(address_component, "street_number"));
				
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lbs;
	}

	private static String getkey(JsonObject address_component, String key) {
		String result = "";
		try {
			result = address_component.getAsJsonObject().get(key).getAsString();
		} catch (Exception e) {
			
		}
		return result;
	}
}
